/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.maxato.xmlservices;

/**
 *
 * @author Danny
 */
import java.net.*;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ConnectToURL {

    // Variables to hold the URL object and its connection to that URL.
    private String cookie;

    @SuppressWarnings("resource")
	String signIn(String username, String password) throws MalformedURLException {
        try {
            URL myUrl = new URL("http://www.maxithlon.com/maxi-xml/login.php?user=" + username + "&scode=" + password + "");
            URLConnection urlConn = myUrl.openConnection();
            urlConn.connect();
            String headerName = null;
            //Cookie zoeken en opslaan
            for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
                if (headerName.equals("Set-Cookie")) {
                    cookie = urlConn.getHeaderField(i);
                    cookie = cookie.substring(0, cookie.indexOf(";"));
                }
            }
            //maken controleer bestand van het inloggen
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String lineRead = "";
            // Read all available lines of data from the URL and print them to screen.
            String alltekst = "";
            while ((lineRead = reader.readLine()) != null) {
                //System.out.println(lineRead);
                alltekst = alltekst + lineRead;
            }
            FileOutputStream fos = new FileOutputStream("data/login.xml");
            new PrintStream(fos).println(alltekst);
            reader.close();
            return cookie;
        } catch (Exception e) {
            return null;
        }
    }

    boolean checkLogin() {
        try {
            File file = new File("data/login.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            //System.out.println("Root element " + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName("maxi-xml");
            //System.out.println("Information of Maxi-xml");

            for (int i = 0; i < nodeLst.getLength(); i++) {

                Node fstNode = nodeLst.item(i);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element fstElmnt = (Element) fstNode;
                    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("login");
                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                    lstNmElmnt.getChildNodes();
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    String getErrorLogin() {
        String error = null;
        try {
            File file = new File("data/login.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            //System.out.println("Root element " + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName("maxi-xml");
            //System.out.println("Information of Maxi-xml");

            for (int i = 0; i < nodeLst.getLength(); i++) {

                Node nNode = nodeLst.item(i);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;
                     error = getTagValue("error", eElement);
   
                }
            }
            return error;
        } catch (Exception e) {
            
            try {
                File errorFile = new File("error.log");
                FileWriter fileWriter = new FileWriter(errorFile);
                fileWriter.write("Date: " + new Date() + " Contact maxatotool@gmail.com." + "\r Error: " + e.toString());
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(ConnectToURL.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            return "Contact maxatotool@gmail.com";
        }
    }

    private String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();

    }
}
